import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/rules.dart';
import 'package:yp/services/api.dart';
import 'package:yp/widgets/index.dart';
import 'package:yp/widgets/task_item.dart';

import '../../router.dart';

///  积分商城
class IntegralMall extends StatefulWidget {
  const IntegralMall({Key key}) : super(key: key);

  @override
  _IntegralMallState createState() => _IntegralMallState();
}

class _IntegralMallState extends State<IntegralMall>
    with TickerProviderStateMixin {
  Map taskDay = {
    'full_message': '',
    'complete_award_sign': 0,
    'complete_activity_sign': 0,
    'sign_in_award_type': 0,
    'sign_in_rule_type': 1,
    'invite_activity_sign': 1,
    'do_tasks': 1
  };
  TabController primaryTC;
  int _length1 = 50;
  List couponList = []; //优惠价数组
  List goodsdtls = []; //商品数组
  String userIntegralNum = '0';
  var userInformationData;
  getCoupon() {
    // 获取用户信息
    var params3 = {
      'access_token': SpUtil.getString('token'),
      'mobile': SpUtil.getString('number'),
    };
    Api.searchMember(params3).listen((event) {
      if (event['code'] == 0) {
        userInformationData = event;
      } else {
        userInformationData = null;
      }
    });

    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
    };

    Api.userIntegral(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          userIntegralNum = event['point'].toString();
        });
      }
    });
    var params = {
      "data_sign": 0,
      "channel_num_id": 98,
      "use_platform": 3,
      "shop_id": 102002001,
      "vip_type_num_id": 1,
      "page": 1,
      "page_size": 10000
    };
    Api.couponQuery(params).listen((event) {
      setState(() {
        if (event['code'] == 0) {
          if (event['scrm_integral_coupon_infos'] != null &&
              event['scrm_integral_coupon_infos'].length > 0) {
            couponList = event['scrm_integral_coupon_infos'];
          }
        }
      });
    });
    var paramss = {
      'access_token': SpUtil.getString('token'),
      "data_sign": 0,
      "channel_num_id": 98,
      "use_platform": 3,
      "shop_id": 102002001,
      "vip_type_num_id": 2222,
      "page": 1,
      "page_size": 10000
    };

    print(">>>>>>>$params");
    Api.reservednoappget(paramss).listen((event) {
      setState(() {
        if (event['code'] == 0) {
          if (event['integral_exchange_goods_dtls'] != null &&
              event['integral_exchange_goods_dtls'].length > 0) {
            print(">>>>>>>$event");

            goodsdtls = event['integral_exchange_goods_dtls'];
          }
        }
      });
    });
    var params2 = {
      "channel_num_id": 98,
      "use_platform": 3,
      "sub_unit_num_id": 102002,
      // "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'access_token': SpUtil.getString('token'),
      "data_sign": 0,
    };
    Api.surpriseDayQuery(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          taskDay = event;
        });
      }
    });
  }

  getShop() {
    var params = {
      "use_platform": 2,
      "access_token": SpUtil.getString('token'),
      "system": "membership",
    };
    Api.membershipInterests(params).listen((event) {
      if (event['code'] == 0) {}
    });
  }

  String setcoupontype(int type) {
    String name = '燃气券';
    switch (type) {
      case 0:
        name = '折扣券';
        break;
      case 1:
        name = '现金券';
        break;
      case 2:
        name = '免邮券';
        break;
      case 8:
        name = '兑换券';
        break;
      case 7:
        name = '燃气券';
        break;
    }
    return name;
  }

  @override
  void initState() {
    super.initState();
    getCoupon();
    getShop();
    primaryTC = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    primaryTC.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: YPNavigationBar('积分商城'),
        body: _buildScaffoldBody(),
        backgroundColor: EsColors.White);
  }

  Widget _buildScaffoldBody() {
    return ExtendedNestedScrollView(
      headerSliverBuilder: (BuildContext c, bool f) {
        return <Widget>[
          SliverToBoxAdapter(
            child: Container(
              width: double.infinity,
              height: 100,
              child: Center(
                child: GestureDetector(
                  onTap: () {
                    Get.toNamed(RouteConfig.myPoints);

                    print('总积分');
                  },
                  child: Container(
                      padding:
                          EdgeInsets.symmetric(vertical: 4, horizontal: 12),
                      child: Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text('总积分',
                                style: TextStyle(
                                    fontSize: EsSizes.XS,
                                    color: EsColors.White,
                                    fontWeight: EsFontWeights.Normal)),
                            SizedBox(height: 6),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(userIntegralNum,
                                    style: TextStyle(
                                        fontSize: 26,
                                        color: EsColors.White,
                                        fontWeight: EsFontWeights.Medium)),
                                SizedBox(width: 4),
                                Icon(
                                  Icons.arrow_forward_ios,
                                  size: EsSizes.SM,
                                  color: EsColors.White,
                                )
                              ],
                            ),
                          ])),
                ),
              ),
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage('assets/images/integral_bg.png'),
                      fit: BoxFit.fill)),
            ),
          ),
          SliverToBoxAdapter(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  color: EsColors.BackGroundSecondary,
                  padding: EdgeInsets.fromLTRB(12, 20, 12, 6),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text('做任务赚积分',
                            style: TextStyle(
                                fontSize: EsSizes.LG,
                                color: EsColors.TitleSecondary,
                                fontWeight: EsFontWeights.Medium)),
                      ),
                      // Text('已完成记录', style: TextStyle(fontSize: EsSizes.SM, color: EsColors.ContentSecondary, fontWeight: EsFontWeights.Normal)),
                      // Icon(
                      //   Icons.arrow_forward_ios,
                      //   size: EsSizes.XS,
                      //   color: EsColors.ContentSecondary,
                      // )
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 12),
                  child: Column(children: [
                    Visibility(
                        visible: rules('a11', taskDay),
                        child: TaskItem(
                            'assets/images/my_task_info.png', '完善信息有礼', '去完善',
                            () {
                          Get.toNamed(RouteConfig.memberInformation,
                              arguments: userInformationData);
                        })),

                    Visibility(
                        visible: rules('a11', taskDay),
                        child: TaskItem(
                            'assets/images/task_signin.png', '每日签到，送积分', '去签到',
                            () {
                          Get.toNamed(RouteConfig.signIn);
                        })),

                    // TaskItem('assets/images/task_stored.png', '签到送积分', '去评论', () {}, subName: '最高可获得80积分'),
                    // TaskItem('assets/images/task_stored.png', '完善信息送积分', '去评论', () {}, subName: '最高可获得80积分'),
                    // TaskItem('assets/images/task_stored.png', '购物送积分', '去评论', () {}, subName: '每消费1元可获得1积分'),
                    // TaskItem('assets/images/task_stored.png', '评价送积分', '去评论', () {}, subName: '每发表1条评价可获得20积分'),
                  ]),
                ),
              ],
            ),
          ),
          SliverToBoxAdapter(
            child: YpLine(height: 20, thickness: 20),
          ),
        ];
      },
      pinnedHeaderSliverHeightBuilder: () {
        return 0;
      },
      onlyOneScrollInBody: true,
      body: Column(
        children: <Widget>[
          TabBar(
            controller: primaryTC,
            labelColor: EsColors.Money,
            indicatorColor: EsColors.Money,
            indicatorSize: TabBarIndicatorSize.tab,
            indicatorWeight: 2.0,
            isScrollable: false,
            unselectedLabelColor: EsColors.ContentSecondary,
            tabs: const <Tab>[
              Tab(text: '兑换优惠券'),
              Tab(text: '兑换商品'),
            ],
          ),
          Expanded(
            child: TabBarView(
                controller: primaryTC,
                children: [_couponList('0'), _goodsList('1')]),
          )
        ],
      ),
    );
  }

  Widget _goodsList(String index) {
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        // mainAxisSpacing: 12,
        // crossAxisSpacing: 12,
        childAspectRatio: 0.7,
      ),
      key: PageStorageKey<String>('Tab' + index),
      // physics: const ClampingScrollPhysics(),
      itemBuilder: (BuildContext c, int i) {
        return GestureDetector(
          onTap: () {
            Get.toNamed(RouteConfig.goodsDetail, arguments: {
              'itemNumId': goodsdtls[i]['item_num_id'].toString(),
              'styleNumId': goodsdtls[i]['style_num_id'].toString(),
              // 'shopId': SpUtil.getInt('storeShopNum').toString(),
              'shopId': goodsdtls[i]['shop_id'].toString(),
              'ecStyleNumId': goodsdtls[i]['item_num_id'].toString(),
              'typeIndex': goodsdtls[i]['is_pre_sale'],
            });
          },
          child: Container(
            decoration: BoxDecoration(
                border:
                    Border.all(color: EsColors.BackGroundSecondary, width: 1)),
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(height: 20),
                CachedImage(
                    width: MediaQuery.of(context).size.width / 2 - 30,
                    height: MediaQuery.of(context).size.width / 2 - 30,
                    path: '${goodsdtls[i]['item_image_url']}'),
                Text(
                  goodsdtls[i]['item_name'],
                  style: TextStyle(
                    fontSize: EsSizes.SM,
                    color: EsColors.TitleSecondary,
                    fontWeight: EsFontWeights.Normal,
                  ),
                  maxLines: 1,
                ),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    RichText(
                        textAlign: TextAlign.start,
                        text: TextSpan(children: [
                          TextSpan(
                              text:
                                  '￥${goodsdtls[i]['integral_exchange_price']}',
                              style: TextStyle(
                                  fontSize: EsSizes.SM,
                                  color: EsColors.Money,
                                  fontWeight: EsFontWeights.Medium)),
                          TextSpan(
                              text:
                                  ' +${goodsdtls[i]['integral_exchange_count']}积分',
                              style: TextStyle(
                                  fontSize: EsSizes.XS,
                                  color: EsColors.Money,
                                  fontWeight: EsFontWeights.Medium)),
                        ])),
                    // Padding(
                    //   padding: const EdgeInsets.all(4.0),
                    //   child: Icon(Icons.monetization_on,
                    //       color: EsColors.Money, size: EsSizes.XS),
                    // ),
                    Text('￥${goodsdtls[i]['price']}',
                        style: TextStyle(
                            decoration: TextDecoration.lineThrough,
                            fontSize: EsSizes.XS,
                            color: EsColors.ContentSecondary,
                            fontWeight: EsFontWeights.Normal)),
                  ],
                ),

                // Text(Key('Tab' + index).toString() + ': ListView$i of $_length1')
              ],
            ),
          ),
        );
      },
      itemCount: goodsdtls.length,
      padding: const EdgeInsets.all(0.0),
    );
  }

  Widget _couponList(String index) {
    return GridView.builder(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        // mainAxisSpacing: 12,
        // crossAxisSpacing: 12,
        childAspectRatio: 0.7,
      ),
      key: PageStorageKey<String>('Tab' + index),
      // physics: const ClampingScrollPhysics(),
      itemBuilder: (BuildContext c, int i) {
        return GestureDetector(
          onTap: () {
            Get.toNamed(
              RouteConfig.coinDetail,
              arguments: {
                'coupon_rule_id': couponList[i]['coupon_rule_id'],
                'score': couponList[i]['integral_plus_count'].toString(),
              },
            );
          },
          child: Container(
            decoration: BoxDecoration(
                border:
                    Border.all(color: EsColors.BackGroundSecondary, width: 1)),
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  // 控件高度
                  constraints:
                      BoxConstraints.expand(height: 360.w, width: 300.w),
                  //设置背景图片
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(new Radius.circular(20.0)),
                    image: DecorationImage(
                      image: ExactAssetImage('assets/images/pro_coupon.png'),
                      // fit: BoxFit.cover,
                      //这里是从assets静态文件中获取的，也可以new NetworkImage(）从网络上获取
                      // centerSlice: Rect.fromLTRB(270.0, 180.0, 1360.0, 730.0),
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Column(
                    children: [
                      SizedBox(
                        height: 50.w,
                      ),
                      Text(
                        setcoupontype(couponList[i]['coupontype']),
                        style: TextStyle(
                            color: Colors.orangeAccent, fontSize: 28.sp),
                      ),
                      SizedBox(
                        height: 80.w,
                      ),
                      Text(
                        '￥${couponList[i]['face_value'] ~/ 1}',
                        style: TextStyle(color: Colors.red, fontSize: 70.sp),
                      ),
                      Text(
                        '全国门店',
                        style: TextStyle(color: Colors.white),
                      )
                    ],
                  ),
                ),
                SizedBox(
                  height: 30.w,
                ),
                Text(couponList[i]['title'],
                    style: TextStyle(
                        fontSize: EsSizes.SM,
                        color: EsColors.TitleSecondary,
                        fontWeight: EsFontWeights.Normal)),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    RichText(
                        textAlign: TextAlign.center,
                        text: TextSpan(children: [
                          TextSpan(
                              text: couponList[i]['integral_plus_count']
                                      .toString() +
                                  "积分",
                              style: TextStyle(
                                  fontSize: EsSizes.SM,
                                  color: EsColors.Money,
                                  fontWeight: EsFontWeights.Medium)),
                        ])),
                    // Padding(
                    //   padding: const EdgeInsets.all(4.0),
                    //   child: Icon(Icons.monetization_on,
                    //       color: EsColors.Money, size: EsSizes.XS),
                    // ),
                  ],
                ),

                // Text(Key('Tab' + index).toString() + ': ListView$i of $_length1')
              ],
            ),
          ),
        );
      },
      itemCount: couponList.length,
      padding: const EdgeInsets.all(0.0),
    );
  }
}
